<!-- DynamicTable.vue -->
<template>
  <div>
    <DynamicSearch
      v-show="showSearch"
      :fields="SearchFormFields"
      class="container-Dynamic"
      @queryList="getList"
    />
    <div class="container-Dynamic dynamic-table">
      <div class="aciton">
        <div class="aciton-item">
          <el-button
            v-for="(item, index) in actions.multiple"
            :key="index"
            :type="item.type || 'primary'"
            :disabled="item.disabled"
            plain
            size="small"
            style="margin: 10px 10px 10px 0"
            @click="item.method ? item.method() : handleTableOpt(item)"
          >
            {{ item.label }}
          </el-button>
          <slot name="button" />
        </div>
<!--        <RightToolbar-->
<!--          :showSearch.sync="showSearch"-->
<!--          :columns="columns"-->
<!--          @queryTable="getList"-->
<!--        ></RightToolbar>-->
      </div>
      <el-table
        :key="tableKey"
        :ref="tableKey"
        :data="tableData"
        v-bind="$attrs"
        v-on="$listeners"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择列 -->
        <el-table-column
          v-if="selection"
          align="center"
          type="selection"
          width="45"
        />

        <!-- 序号列 -->
        <el-table-column
          v-if="showIndex"
          align="center"
          label="序号"
          type="index"
          width="55"
          fixed="left"
        >
          <template slot-scope="scope">
            {{ (pagination.page - 1) * pagination.limit + scope.$index + 1 }}
          </template>
        </el-table-column>

        <!-- 动态列 -->
        <div >
          <DynamicColumn v-for="(column, i) in processedColumns" :key="i" :column="column" :table-key="`${i}`" />
        </div>

        <!-- 操作列 -->
        <el-table-column
          v-if="actions.single && actions.single.length"
          :width="actionsWidth"
          align="center"
          fixed="right"
          label="操作"
        >
          <template slot-scope="{ row }">
            <div class="dynamic-action-buttons">
              <template v-for="action in filteredActions(row)">
                <el-button
                  v-if="!(action.vIf && !action.vIf(row))"
                  :icon="action.icon"
                  :type="action.type || 'text'"
                  size="mini"
                  @click="handleActionClick(action, row)"
                >
                  {{ action.label }}
                </el-button>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <Pagination
        v-if="pagination"
        :total.sync="pagination.total"
        :page.sync="pagination.page"
        :page-size.sync="pagination.limit"
        @pagination="handlePageChange"
      />
    </div>
  </div>
</template>

<script>
import DynamicColumn from "./DynamicColumn.vue";
import Pagination from "./Pagination/index.vue";
import DynamicSearch from "../Search/index.vue";
import RightToolbar from "./RightToolbar/index.vue";
// import request from "@/utils/request";

export default {
  name: "DynamicTable",
  components: { DynamicColumn, Pagination, DynamicSearch,RightToolbar },
  props: {
    TableConfig: {
      type: Object,
      default: () => {},
    },
    SearchFormFields: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      tableKey: String(Math.floor(Math.random() * 10000)).padStart(4, "0"),
      columns: [], // 列配置
      tableData: [], // 表格数据
      actions: {
        single: [],
        multiple: [],
      }, // 操作按钮配置
      selection: true, // 是否显示选择列
      showIndex: true, // 是否显示序号列
      pagination: {
        limit: 10, // 每页条数
        page: 1, // 当前页
        total: 0, // 总条目数
      }, // 是否显示分页
      immediate: true, // 是否默认请求数据
      ...this.TableConfig,
      showSearch: true, // 显示搜索条件
    };
  },
  computed: {
    filteredActions() {
      return (row) => {
        return this.actions.single?.filter((action) =>
          typeof action.visible === "function"
            ? action.visible(row)
            : action.visible !== false
        );
      };
    },
    actionsWidth() {
      let w = 0;
      this.actions.single?.forEach((e) => {
        if (e.label) {
          w = w + e.label.length;
        }
      });
      return w * 34 > 240 ? "240px" : w * 34 + "px";
    },
    processedColumns() {
      return this.columns
        .map((col) => {
          // 如果 visible 不为 true，直接过滤掉（返回 null）
          // if (!col.visible) return null;
          // 保留可见列，并递归处理子列
          return {
            align: "center",
            minWidth: 120,
            maxWidth: 240,
            ...col, // 原有列属性覆盖默认值（如 col.align 会覆盖 "center"）
            children: col.children ? this.processedColumns(col.children) : null, // 递归处理子列
          };
        })
        .filter(Boolean); // 过滤掉 null/undefined
    },
    windowWidth() {
      return window.innerWidth;
    },
  },
  watch: {
    windowWidth(newVal, oldVal) {
      if (newVal !== oldVal) {
        console.log("窗口大小已改变");
        // this.$refs[this.tableKey].doLayout()
        // 在这里执行你需要执行的代码
      }
    },
  },
  updated() {
    this.$nextTick(() => {
      this.$refs[this.tableKey].doLayout(); // 解决表格行错位
    });
  },
  mounted() {
    this.$nextTick(() => {
      if (this.immediate) {
        // this.getList();
      }
    });
  },
  methods: {
    compare(x, y) {
      //比较函数
      if (x < y) {
        return -1;
      } else if (x > y) {
        return 1;
      } else {
        return 0;
      }
    },
    getList(params = {}) {
      this.queryFrom = params;
      this.Request(this.TableConfig.list, {
        ...this.pagination,
        ...params,
      }).then((res) => {
        if ([200].includes(res.code)) {
          const response = this._returnResponse(res);
          this.tableData = this._returnListData(res);
          this.pagination.total = response.total;
          this.$refs[this.tableKey].doLayout();
        }
      });
    },
    Request(config, params = {}) {
      if (!config?.url) {
        console.warn(`[Request] Missing URL config for config: ${config}`);
        return Promise.reject(new Error("Invalid request config"));
      }
      const METHOD_HANDLERS = {
        PUT: (url, { id, ...data }) => ({ url: `${url}/${id}`, data }),
        POST: (url, params) => ({ url, data: params }),
        DELETE: (url, { id, ...data }) => ({ url: `${url}/${id}`, data }),
        GET: (url, params) => ({ url, params }),
      };
      const method = config.method || "GET";
      const handler = METHOD_HANDLERS[method];
      if (!handler) {
        return Promise.reject(new Error(`Unsupported method: ${method}`));
      }
      const { url, ...requestArgs } = handler(config.url, params);
      // return request({
      //   url,
      //   method,
      //   ...requestArgs,
      // }).catch((err) => {
      //   console.error(`[Request Failed] ${method} ${url}`, err);
      //   throw err;
      // });
    },
    // 返回列表值
    _returnListData(response) {
      if (!this.TableConfig.list.dataParam) return response.data;
      const arr = this.TableConfig.list.dataParam.split(".");
      arr.forEach((item) => {
        response = response[item];
      });
      return response;
    },
    // 返回接口返回值
    _returnResponse(response) {
      if (!this.TableConfig.list.resultParam) return response;
      const arr = this.TableConfig.list.resultParam.split(".");
      arr.forEach((item) => {
        response = response[item];
      });
      return response;
    },
    processColumns(columns) {
      return columns.map((col) => ({
        // 默认配置
        align: "center",
        minWidth: 120,
        headerAlign: "center",
        showOverflowTooltip: true,
        // 合并用户自定义配置
        ...col,
        // 递归处理子列
        children: col.children ? this.processColumns(col.children) : undefined,
      }));
    },
    // 选择列
    handleSelectionChange(selection) {
      this.$emit("selection-change", selection);
    },
    // 分页
    handlePageChange(page) {
      this.$emit("update:page", page);
      this.pagination.page = page;
      this.getList(this.queryFrom);
    },
    // 表格操作
    handleTableOpt(item) {
      if (item.method) return item.method(item);
      if (this.TableConfig.deletes) {
        // 批量删除
        this.deletes(this.TableConfig.deletes, { ids: "" });
      }
      if (this.TableConfig.import) {
        /** 导入按钮操作 */
      }
    },
    // 列表操作
    handleActionClick(action, row) {
      if (action.method) return action.method(row);
      if (action.delete) {
        // 单条删除
        this.deletes(this.TableConfig.delete, { id: row.id });
      }
    },
    deletes(config, params) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.Request(config, params).then((res) => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-table__body-wrapper {
  overflow-y: auto !important;
}
</style>
